package org.team4.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.team4.constants.SQLConstant;
import org.team4.constants.StringConstant;
import org.team4.dao.DAOFactory;
import org.team4.dao.UsersDAO;
import org.team4.domain.Users;
import org.team4.exception.CRUDException;
import org.team4.util.FileHelper;
import org.team4.util.ImageHelper;
import org.team4.util.LoginBean;
import org.team4.util.Meta;
import org.team4.util.Validate;
import org.team4.vo.Page;
import org.team4.vo.UserVO;

import com.opensymphony.xwork2.ActionContext;

@Service
public class UsersService implements IService {

    private UsersDAO usersDAO;

    @Autowired
    public void setSessionFactory(SessionFactory sessionFactory) {
        usersDAO = (UsersDAO) DAOFactory.getDAO(sessionFactory, UsersDAO.class);
    }

    /**
     * 用户登录
     * 
     * @param accountName
     * @param password
     * @return
     * @throws CRUDException
     */
    public Users saveLogin(String accountName, String password) throws CRUDException {
        Users users = null;
        List<Users> usersList = usersDAO.find("from Users where accountName = ? and password = ?", accountName, password);
        if (Validate.collectionNotNull(usersList))
            users = usersList.get(0);
        return users;
    }

    /**
     * 登出
     * 
     * @throws CRUDException
     */
    public void saveLogout() throws CRUDException {
        ActionContext.getContext().getSession().remove("LoginBean");
    }

    /**
     * 验证用户名是否存在(存在:true,不存在:false)
     * 
     * @param accountName
     * @return
     * @throws CRUDException
     */
    public boolean accountNameExist(String accountName) throws CRUDException {
        List userList = usersDAO.findByProperty("accountName", accountName);
        return Validate.collectionNotNull(userList);
    }

    /**
     * 查找所有用户
     * 
     * @return
     * @throws CRUDException
     */
    public List<Users> findAllUsers() throws CRUDException {
        return usersDAO.find(SQLConstant.USERS_ALL_HQL);
    }

    /**
     * 根据真实姓名模糊查找用户
     * 
     * @param realName
     * @return
     * @throws CRUDException
     */
    public List<Users> findUsersLikeRealName(String realName) throws CRUDException {
        if (Validate.notNull(realName)) {
            return usersDAO.findOrder(SQLConstant.USERS_LIKE_REALNAME_HQML, "realName", "%" + realName + "%");
        } else {
            return usersDAO.find(SQLConstant.USERS_ALL_HQL);
        }
    }
    
    public List<Users> findMetaUsersLikeRealName(String realName, String moduleId) throws CRUDException {
    	if (Validate.notNull(realName)) {
            return usersDAO.findOrder(SQLConstant.USERS_LIKE_REALNAME_HQML + SQLConstant.getSQLInString(Meta.getUsers(moduleId), "id", "and"), "realName", "%" + realName + "%");
        } else {
            return usersDAO.findOrder(SQLConstant.USERS_ALL_H_HQL + SQLConstant.getSQLInString(Meta.getUsers(moduleId), "id", "and"), "realName");
        }
    }

    /**
     * 查找真实姓名,以","分隔显示
     * 
     * @param userIds
     * @return
     * @throws CRUDException
     */
    public String findUserByAccountNames(String userIds) throws CRUDException {
        if (Validate.notNull(userIds)) {
            StringBuffer realNames = new StringBuffer();
            String[] splitIds = userIds.split(",");
            for (int i = 0; i < splitIds.length; i++) {
                Users user = usersDAO.get(splitIds[i]);
                if (user != null) {
                    if (i == 0) {
                        realNames.append(user.getRealName());
                    } else {
                        realNames.append(",");
                        realNames.append(user.getRealName());
                    }
                }
            }
            return realNames.toString();
        } else {
            return "";
        }
    }

    /**
     * 拼接前台用户展现
     * 
     * @param userIds
     * @return
     * @throws CRUDException
     */
    public String findUserLinks(String userIds) throws CRUDException {
        if (Validate.notNull(userIds)) {
            StringBuffer realNames = new StringBuffer();
            realNames.append("<div class=\"link_content_inner\">");
            String[] splitIds = userIds.split(",");
            for (int i = 0; i < splitIds.length; i++) {
                Users user = usersDAO.get(splitIds[i]);
                if (user != null) {
                    realNames.append("<div><a href=\"javascript:void(0)\">");
                    realNames.append(user.getRealName());
                    realNames.append("</a></div>");
                }
            }
            realNames.append("</div>");
            return realNames.toString();
        } else {
            return "&nbsp;";
        }
    }

    /**
     * 查找除自己以外的所有用户
     * 
     * @return
     * @throws CRUDException
     */
    public List<Users> findAllUsersNotSelf() throws CRUDException {
        return usersDAO.find(SQLConstant.USERS_NOSELF_ALL_HQL, LoginBean.getLoginBean().getUser().getId());
    }

    /**
     * 根据首字符拼音查询
     * 
     * @param page
     * @param property
     * @param azparam
     * @return
     * @throws CRUDException
     */
    public Page<Users> paginationByPY(Page<Users> page, String property, String azparam) throws CRUDException {
        return usersDAO.pagination(page, SQLConstant.getAZHQL("Users", property, azparam), null);
    }

    /**
     * 根据ID查找用户
     * 
     * @param userId
     * @return
     * @throws Exception
     */
    public Users findById(String userId) throws CRUDException {
        return usersDAO.get(userId);
    }

    /**
     * 创建新用户
     * 
     * @param user
     * @throws CRUDException
     */
    public void saveUsers(Users user, String imagePath, String targetPath) throws CRUDException {
        user.setCreator(LoginBean.getLoginBean().getUser());
        user.setCreateTime(new Date());
        user.setState(user.getState());
        if(Validate.notNull(imagePath)) {
        	user.setBigImage(getImagePath(imagePath, targetPath, Users.BIG_IMAGE));
        	user.setNormalImage(getImagePath(imagePath, targetPath, Users.NORMAL_IMAGE));
        	user.setSmallImage(getImagePath(imagePath, targetPath, Users.SMALL_IMAGE));
        }
        usersDAO.save(user);
    }
    
    /**
     * 修改用户信息
     * 
     * @param user
     * @throws CRUDException
     */
    public void updateUsers(Users user, String imagePath, String targetPath) throws CRUDException {
        Users oldUser = usersDAO.get(user.getId());
        oldUser.setPassword(user.getPassword());
        oldUser.setSex(user.getSex());
        oldUser.setBirthday(user.getBirthday());
        oldUser.setState(user.getState());
        oldUser.setRealName(user.getRealName());
        oldUser.setDepartment(user.getDepartment());
        oldUser.setEditor(LoginBean.getLoginBean().getUser());
        oldUser.setEditTime(new Date());
        if(Validate.notNull(imagePath)) {
        	oldUser.setBigImage(getImagePath(imagePath, targetPath, Users.BIG_IMAGE));
        	oldUser.setNormalImage(getImagePath(imagePath, targetPath, Users.NORMAL_IMAGE));
        	oldUser.setSmallImage(getImagePath(imagePath, targetPath, Users.SMALL_IMAGE));
        }
        usersDAO.update(oldUser);
        
    }
    
    /**
     * 生成图片，获得文件路径
     * @param imagePath
     * @param targetPath
     * @param imageSize
     * @return
     */
    private String getImagePath(String imagePath, String targetPath, int imageSize) {
    	String path = ImageHelper.scaleResize(imagePath, targetPath, imageSize);
    	if(Validate.notNull(path)) {
    		String shortPath = path.split(Users.PIC_FOLDER)[1];
    		return FileHelper.SEPARATOR + Users.PIC_FOLDER + FileHelper.SEPARATOR + shortPath.substring(1, shortPath.length());
    	} else {
    		return "";
    	}
    }

    /**
     * 修改密码
     * 
     * @param id
     * @param newPassword
     * @throws CRUDException
     */
    public void updateUsersPassword(String id, String newPassword) throws CRUDException {
        Users user = usersDAO.get(id);
        user.setEditor(LoginBean.getLoginBean().getUser());
        user.setEditTime(new Date());
        user.setPassword(newPassword);
        usersDAO.update(user);
    }

    /**
     * 修改用户状态
     * 
     * @param id
     * @param state
     * @throws CRUDException
     */
    public void updateUsersState(String id, String state) throws CRUDException {
        Users user = usersDAO.get(id);
        user.setState(state);
        user.setEditor(LoginBean.getLoginBean().getUser());
        user.setEditTime(new Date());
        usersDAO.update(user);
    }

    /**
     * 删除
     * 
     * @param idList
     * @throws Exception
     */
    public void deleteUsers(List<String> idList) throws CRUDException {
        if (Validate.collectionNotNull(idList)) {
        	for (String id : idList) {
        		Users user = usersDAO.get(id);
        		user.setState(StringConstant.FALSE);
        		usersDAO.update(user);
			}
        }
    }

    /**
     * 分页
     * 
     * @param page
     * @return
     * @throws CRUDException
     */
    public Page<Users> listPagination(Page<Users> page, String deptId) throws CRUDException {
        if (Validate.notNull(deptId))
            return usersDAO.pagination(page, SQLConstant.USERS_DEPT_H_HQL, null, deptId);
        else
            return usersDAO.pagination(page, SQLConstant.USERS_ALL_H_HQL, null);
    }
    
    public List<UserVO> findUsersByIds(String ids) throws CRUDException {
    	List<UserVO> uList = new ArrayList<UserVO>();
    	String[] s = ids.split(",");
    	for(int i = 0; i < s.length; i++) {
    		if(Validate.notNull(s[i])) {
    			Users u = usersDAO.get(s[i]);
    			UserVO v = new UserVO();
    			v.setUserId(u.getId());
    			v.setRealName(u.getRealName());
    			uList.add(v);
    		}
    	}
    	return uList;
    }
}